<template>
  <el-dialog v-model="visible" title="创建企业">
    <create-form @submit="createUser" @cancel="close"></create-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import CreateForm from './form.vue'
import api from '@/http/index.js'
import { ElMessage } from 'element-plus'
const visible = ref(false)
let resolvePromise = null
let rejectPromise = null

const createUser = async (data) => {
  api.enterprise
    .create({
      ...data,
      ...userData,
    })
    .then(({ data = {} } = {}) => {
      ElMessage({
        message: '创建企业成功',
        type: 'success',
      })
      resolvePromise(data)
    })
    .catch(() => {
      ElMessage({
        message: '创建企业失败',
        type: 'error',
      })
      rejectPromise()
    })
    .finally(() => {
      close()
    })
}

const close = () => {
  visible.value = false
  resolvePromise()
  resolvePromise = null
  rejectPromise = null
}

let userData = reactive({})
const open = (user) => {
  console.log(user)
  if (!user?.userId) {
    ElMessage({
      message: '请先创建用户',
      type: 'error',
    })
    return Promise.reject()
  }
  visible.value = true
  userData = user
  resolvePromise = null
  rejectPromise = null
  return new Promise((resolve, reject) => {
    resolvePromise = resolve
    rejectPromise = reject
  })
}

defineExpose({
  open,
  close,
})
</script>

<style lang="scss"></style>
